﻿//-----------------------------------------------------------------------
// <copyright file="ApplicationCopier.cs" company="n.a.">
//     Copyright Dave999. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "To be returned to .")]

namespace DbView
{
	using System;
	using System.IO;
	using System.Xml;

	internal class ApplicationCopier
	{
		// just do the logic to get the new nme
		internal static string PortableExeName(string destinationPathFolder, string folderName)
		{
			string destination = Path.Combine(destinationPathFolder, folderName);
			string exeOnDestination = Path.Combine(destination, ApplicationEnvironment.ProgramName);
			return exeOnDestination;
		}

		// find the deepest foldername
		internal static string DocumentFolderName()
		{
			string fullName = ApplicationEnvironment.DocumentFolder;
			string[] parts = fullName.Split('\\');
			int lastPart = parts.GetLength(0) - 1;  // get length in case we ever find the need to test it before continuing
			return parts[lastPart];                 // On development it will always have a folder name to return
		}

		// find the deepest foldername
		internal static string DataFolderName()
		{
			string fullName = ApplicationEnvironment.DataFolder; // always the appdata location whether portable or not
			string[] parts = fullName.Split('\\');
			int lastPart = parts.GetLength(0) - 1;  // get length in case we ever find the need to test it before continuing
			return parts[lastPart];                 // On development it will always have a folder name to return
		}

		internal static bool Copy(string destinationPathFolder, string folderName, bool copyConfig, bool copyDocs, out string message)
		{
			// final destination
			string destination = Path.Combine(destinationPathFolder, folderName);

			// optimist
			message = "Copy complete. The new system is in " + destination;

			// 1. test whether folder exists
			if (!Directory.Exists(destinationPathFolder))
			{
				message = string.Format("Destination folder not found:\n{0}", destinationPathFolder);
				return false;
			}

			// 2. Attempt to create the folder
			if (!Directory.Exists(destination))
			{
				try
				{
					Directory.CreateDirectory(destination); // will throw if there is a permissions problem or anything
				}
				catch (Exception ex1)
				{
					message = string.Format("Could not create {1}. Message returned is\n{0}", ex1.Message, destination);
					return false;
				}
			}

			// 3. System cannot already be there
			string exeOnDestination = Path.Combine(destinationPathFolder, ApplicationEnvironment.ProgramName);
			if (File.Exists(exeOnDestination))
			{
				message = string.Format("{0} already exists.\nAn overwrite is not permitted.", exeOnDestination);
				return false;
			}

			// 4. attempt to copy the system
			string[] filePaths = Directory.GetFiles(ApplicationEnvironment.ProgramFolder);
			try
			{
				foreach (string file in filePaths)
				{
					File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));
				}
			}
			catch (Exception ex1)
			{
				message = string.Format("Could not transfer application\nfrom {2}\n  to {1}.\n Message returned is\n{0}", ex1.Message, destination, ApplicationEnvironment.ProgramFolder);
				return false;
			}

			// Config
			string configDestination = Path.Combine(destination, ApplicationEnvironment.ConfigFileName);
			if (copyConfig)
			{
				DbView.Resources.ConfigDoc.Instance.SaveConfig(configDestination);

				// copy templates if they exist
				string templateFile = Path.Combine(ApplicationEnvironment.DataFolder, ApplicationEnvironment.TemplateFileName);
				if (File.Exists(templateFile))
				{
					string destinationTemplateFile = Path.Combine(destination, ApplicationEnvironment.TemplateFileName);
					try
					{
						File.Copy(templateFile, destinationTemplateFile);
					}
					catch (Exception ex1)
					{
						message = string.Format("Could not transfer templates\nfrom {2}\n to {1}.\n Message returned is\n{0}", ex1.Message, destination, ApplicationEnvironment.ProgramFolder);
					}
				}
			}
			else
			{
				XmlDocument blankDoc = new XmlDocument();

				// Add root element
				XmlNode node = blankDoc.CreateElement(DbView.Resources.ConfigDoc.CFGELM_DOC);
				blankDoc.AppendChild(node);
				blankDoc.Save(configDestination);
			}

			// Documents (later)
			if (copyDocs)
			{
				string docPath = ApplicationEnvironment.DocumentFolder;
				string docSubFolder = DocumentFolderName();
				if (Directory.Exists(docPath))
				{
					string docDestination = Path.Combine(destination, docSubFolder);

					// make a destination document file
					try
					{
						Directory.CreateDirectory(docDestination); // will throw if there is a permissions problem or anything
					}
					catch (Exception)
					{
						message = string.Format("System copied, but documents were not");
						return true;
					}

					// 5. attempt to copy the doc files
					filePaths = Directory.GetFiles(docPath);
					try
					{
						foreach (string file in filePaths)
						{
							File.Copy(file, Path.Combine(docDestination, Path.GetFileName(file)));
						}
					}
					catch (Exception)
					{
						message = string.Format("System copied, but documents were not");
						return true;
					}
				}
			}

			return true;
		}
	}
}
